package com.formation.userbase.persistance.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;

import com.formation.userbase.persistance.beans.User;

@Service(value="userdaobean")
public class UserHibernateDao implements UserDao {
	
	@Resource(name="mysessionfactory")
	SessionFactory sessF;
	
	public UserHibernateDao() {
		// TODO Auto-generated constructor stub
	}
	
	
	
	 public SessionFactory getSessF() {
		return sessF;
	}



	public void setSessF(SessionFactory sessF) {
		this.sessF = sessF;
	}



	public boolean insert(User u){
			Session session = sessF.openSession();;
			Transaction tx=null;
			try {
				//System.out.println("heeee"+u.getLogin());
				tx = session.beginTransaction();
				session.save(u);
				tx.commit();
				return true;
			} catch (RuntimeException e) {
				//if(tx != null) tx.rollback();
				e.printStackTrace();
				return false;
			} finally {
				session.close();
			}
		
	 }
	 public User findUserByLogin(String Login){
		 	Session session = sessF.openSession();;
	    	try {
				//session.beginTransaction();
			//Query q = session.createSQLQuery("Select EVENT_ID, EVENT_DATE, title from events e where e.EVENT_ID =:eventId");
	    		
	    		Query q = session.createQuery("from User as u where u.login =:monLogin");
	    		q.setString("monLogin", Login);
	    	    
			return (User) q.uniqueResult();
	    	}catch (RuntimeException e) {
			//if(tx != null) tx.rollback();
			return null;
	    	}
	    	finally {
				session.close();
			}
	 }
	 public List<User> getAllUser(){
		 	Session session = sessF.openSession();;
	    	try {
				//session.beginTransaction();
			//Query q = session.createSQLQuery("Select EVENT_ID, EVENT_DATE, title from events e where e.EVENT_ID =:eventId");
	    		
	    		Query q = session.createQuery("from User as u ");
	    		
	    	    
			return  (List<User>)q.list();
	    	}catch (RuntimeException e) {
			//if(tx != null) tx.rollback();
			return null;
	    	}
	    	finally {
				session.close();
			}
		 
	 }
	
	
}
